<template>
    <!-- 新增：科技感加载动画 -->
    <div v-if="loading" class="tech-loading-overlay">
        <div class="tech-loading-grid"></div>
        <div class="tech-loading-core">
            <div class="tech-loading-orb"></div>
            <div class="tech-loading-ring"></div>
            <div class="tech-loading-particles">
                <div v-for="n in 12" :key="n" class="tech-particle"></div>
            </div>
        </div>
        <div class="tech-loading-text">
            <span>加载中</span>
            <span class="tech-loading-dots"> <span>.</span><span>.</span><span>.</span> </span>
        </div>
    </div>

    <!-- 原有内容保持不变 -->
    <div
        class="max-w-6xl mx-auto bg-slate-900/80 rounded-xl shadow-lg overflow-hidden p-8 backdrop-blur-sm border border-indigo-500/30 tech-card animate-fade-in"
    >
        <div class="tech-decorations">
            <div class="tech-corner top-left"></div>
            <div class="tech-corner top-right"></div>
            <div class="tech-corner bottom-left"></div>
            <div class="tech-corner bottom-right"></div>
            <div class="tech-circuit"></div>
        </div>
        <h2 class="text-2xl font-bold text-center text-indigo-200 mb-8 glow-text">您的九型人格测试结果</h2>

        <!-- Summary -->
        <div class="bg-indigo-900/30 rounded-lg p-6 mb-8 border border-indigo-500/30 summary-card">
            <h3 class="text-xl font-semibold text-indigo-200 mb-4 glow-text-sm">测试摘要</h3>
            <div class="grid grid-cols-2 gap-4">
                <div class="p-3 bg-slate-800/50 rounded-lg border border-indigo-500/20">
                    <p class="text-slate-300">
                        <span class="font-medium text-indigo-300">主要类型:</span> {{ result.mainEnneagram?.name || '无法确定' }}
                    </p>
                    <p class="text-slate-300">
                        <span class="font-medium text-indigo-300">得分:</span>
                        <span class="text-indigo-200 font-semibold">{{ result.raw_scores[result.main_type] }}</span>
                    </p>
                </div>
                <div class="p-3 bg-slate-800/50 rounded-lg border border-indigo-500/20">
                    <p class="text-slate-300">
                        <span class="font-medium text-indigo-300">侧翼:</span> {{ result.wingEnneagram?.name || '无明显倾向' }}
                    </p>
                    <p class="text-slate-300">
                        <span class="font-medium text-indigo-300">得分:</span>
                        <span class="text-indigo-200 font-semibold">{{ result.raw_scores[result.wing_type] || '0' }}</span>
                    </p>
                </div>
            </div>
        </div>

        <!-- Charts -->
        <div class="mb-8">
            <h3 class="text-xl font-semibold text-indigo-200 mb-4 glow-text-sm">人格特质分布</h3>
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
                <div class="h-96 bg-slate-800/50 rounded-lg p-4 border border-indigo-500/20 chart-container">
                    <div ref="radarChart" class="w-full h-full"></div>
                </div>
                <div class="h-96 bg-slate-800/50 rounded-lg p-4 border border-indigo-500/20 chart-container">
                    <div ref="barChart" class="w-full h-full"></div>
                </div>
            </div>
        </div>

        <!-- Detailed Report -->
        <div>
            <h3 class="text-xl font-semibold text-indigo-200 mb-4 glow-text-sm">详细分析</h3>

            <div class="mb-6 bg-slate-800/50 rounded-lg p-4 border border-indigo-500/20 report-section">
                <h4 class="text-lg font-medium text-indigo-300 mb-2">{{ result.mainEnneagram?.name || '' }}人格特征</h4>
                <p class="text-slate-300" v-for="(desc, index) in result.mainEnneagram?.description" :key="index">{{ desc }}</p>
            </div>

            <div class="mb-6 bg-slate-800/50 rounded-lg p-4 border border-indigo-500/20 report-section">
                <h4 class="text-lg font-medium text-indigo-300 mb-2">您的性格优势</h4>
                <ul class="list-disc pl-6 space-y-2 text-slate-300">
                    <li v-for="(strength, index) in result.mainEnneagram?.strengths" :key="index" class="strength-item">{{ strength }}</li>
                </ul>
            </div>

            <div class="mb-6 bg-slate-800/50 rounded-lg p-4 border border-indigo-500/20 report-section">
                <h4 class="text-lg font-medium text-indigo-300 mb-2">发展建议</h4>
                <ul class="list-disc pl-6 space-y-2 text-slate-300">
                    <li v-for="(suggestion, index) in result.mainEnneagram?.suggestions" :key="index" class="suggestion-item">{{ suggestion }}</li>
                </ul>
            </div>
            <!-- <div class="mb-6 bg-slate-800/50 rounded-lg p-4 border border-indigo-500/20 report-section">
                <h4 class="text-lg font-medium text-indigo-300 mb-2">其他描述</h4>
                <ul class="list-disc pl-6 space-y-2 text-slate-300">
                    <li v-for="(other, index) in result.mainEnneagram?.other" :key="index" class="suggestion-item">{{ other }}</li>
                </ul>
            </div> -->
        </div>

        <!-- Actions -->
        <div class="mt-8 flex justify-center space-x-4">
            <!-- <button
                class="tech-button whitespace-nowrap bg-gradient-to-r from-indigo-600 to-indigo-500 hover:from-indigo-500 hover:to-indigo-400 text-white font-medium py-2 px-6 relative overflow-hidden"
            >
                <span class="relative z-10">保存报告</span>
                <span class="button-glow"></span>
            </button> -->
            <button
                @click="$router.push({ name: '/' })"
                class="tech-button-secondary whitespace-nowrap bg-transparent hover:bg-slate-800 text-indigo-300 font-medium py-2 px-6 border border-indigo-500 transition-all duration-300"
            >
                重新测试
            </button>
        </div>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, nextTick, reactive, onUnmounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import * as echarts from 'echarts'
import { report } from '/@/api/frontend/enneagram/index'

// 常量定义
const LOADING_DELAY = 2000
const CHART_COLORS = ['#4F46E5', '#6366F1', '#818CF8', '#A5B4FC', '#C7D2FE', '#E0E7FF', '#ECFDF5', '#D1FAE5', '#A7F3D0']
const DEFAULT_ENNEAGRAM_TYPE = { name: '', type: '', description: [], strengths: [], suggestions: [], other: [] }

// 类型定义
interface EnneagramType {
    name: string
    type: string
    description: string[]
    strengths: string[]
    suggestions: string[]
    other: string[]
}

interface ResultType {
    scores: number[]
    raw_scores: number[]
    main_type: number
    wing_type: number
    mainEnneagram?: EnneagramType
    wingEnneagram?: EnneagramType
}

// 响应式数据
const loading = ref(true)
const result = reactive<ResultType>({
    scores: Array(9).fill(0),
    raw_scores: Array(9).fill(0),
    main_type: 0,
    wing_type: 0,
    mainEnneagram: DEFAULT_ENNEAGRAM_TYPE,
    wingEnneagram: DEFAULT_ENNEAGRAM_TYPE,
})

let enneagramTypes: EnneagramType[] = []
let loadingTimer: NodeJS.Timeout | null = null
let chartInstances: echarts.ECharts[] = []

// 模板引用
const radarChart = ref<HTMLElement | null>(null)
const barChart = ref<HTMLElement | null>(null)

// 路由
const route = useRoute()
const router = useRouter()

// 获取报告ID
const getReportId = () => route.params.id || route.query.id

// 创建雷达图配置
const createRadarConfig = () => ({
    animation: true,
    radar: {
        indicator: enneagramTypes.map((type) => ({
            name: type.type + type.name,
            max: 100,
        })),
        radius: '70%',
    },
    series: [
        {
            type: 'radar',
            data: [
                {
                    value: Object.values(result.scores),
                    name: '人格特质得分',
                    areaStyle: { color: 'rgba(79, 70, 229, 0.2)' },
                    lineStyle: { color: 'rgba(79, 70, 229, 1)' },
                    symbolSize: 8,
                },
            ],
        },
    ],
})

// 创建柱状图配置
const createBarConfig = () => ({
    animation: true,
    xAxis: {
        type: 'category',
        data: enneagramTypes.map((type) => type.name),
        axisLabel: { interval: 0, rotate: 30 },
    },
    yAxis: { type: 'value', max: 100 },
    series: [
        {
            data: Object.values(result.scores),
            type: 'bar',
            itemStyle: {
                color: (params: any) => CHART_COLORS[params.dataIndex] || CHART_COLORS[0],
            },
        },
    ],
})

// 初始化图表
const initCharts = () => {
    if (!radarChart.value || !barChart.value) return

    try {
        // 清理现有实例
        chartInstances.forEach((instance) => instance.dispose())
        chartInstances = []

        // 创建新实例
        const radarInstance = echarts.init(radarChart.value)
        const barInstance = echarts.init(barChart.value)

        chartInstances.push(radarInstance, barInstance)

        // 设置配置
        radarInstance.setOption(createRadarConfig())
        barInstance.setOption(createBarConfig())
    } catch (error) {
        console.error('图表初始化失败:', error)
    }
}

// 处理窗口大小变化
const handleResize = () => {
    chartInstances.forEach((instance) => {
        try {
            instance.resize()
        } catch (error) {
            console.error('图表大小调整失败:', error)
        }
    })
}

// 清理资源
const cleanup = () => {
    if (loadingTimer) {
        clearTimeout(loadingTimer)
        loadingTimer = null
    }

    chartInstances.forEach((instance) => {
        try {
            instance.dispose()
        } catch (error) {
            console.error('图表清理失败:', error)
        }
    })
    chartInstances = []

    window.removeEventListener('resize', handleResize)
}
// 更新结果数据
const updateResultData = (reportData: any) => {
    Object.assign(result, {
        scores: reportData.scores || Array(9).fill(0),
        raw_scores: reportData.raw_scores || Array(9).fill(0),
        main_type: reportData.main_type || 0,
        wing_type: reportData.wing_type || 0,
        mainEnneagram: reportData.mainEnneagram,
        wingEnneagram: reportData.wingEnneagram,
    })
}
// 生命周期钩子
onMounted(async () => {
    // 设置加载定时器
    loadingTimer = setTimeout(() => {
        loading.value = false
    }, LOADING_DELAY)

    try {
        const response = await report({ id: getReportId() })

        // 处理支付重定向
        if (response?.data?.pay_is_required) {
            router.push({ name: 'pay', params: { id: response.data.id } })
            return true
        }

        // 更新数据
        updateResultData(response.data.report)
        enneagramTypes = response.data.enneagramTypes || []

        // 初始化图表
        await nextTick()
        initCharts()

        // 监听窗口大小变化
        window.addEventListener('resize', handleResize)
    } catch (error) {
        console.error('获取报告失败:', error)
        enneagramTypes = []
    } finally {
        if (loadingTimer) {
            clearTimeout(loadingTimer)
            loadingTimer = null
        }
        loading.value = false
    }
})

onUnmounted(() => {
    cleanup()
})
</script>

<style scoped lang="scss">
/* 新增：科技感加载动画样式 */
.tech-loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: linear-gradient(135deg, #0f172a 0%, #1e293b 100%);
    z-index: 9999;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    overflow: hidden;
}

.tech-loading-grid {
    position: absolute;
    width: 100%;
    height: 100%;
    background-image: linear-gradient(rgba(99, 102, 241, 0.1) 1px, transparent 1px),
        linear-gradient(90deg, rgba(99, 102, 241, 0.1) 1px, transparent 1px);
    background-size: 40px 40px;
    animation: gridMove 20s linear infinite;
}

.tech-loading-core {
    position: relative;
    width: 200px;
    height: 200px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.tech-loading-orb {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    background: radial-gradient(circle, rgba(79, 70, 229, 0.8) 0%, transparent 70%);
    box-shadow: 0 0 40px rgba(79, 70, 229, 0.6);
    animation: pulse 2s ease-in-out infinite alternate;
}

.tech-loading-ring {
    position: absolute;
    width: 160px;
    height: 160px;
    border: 2px solid rgba(79, 70, 229, 0.5);
    border-radius: 50%;
    animation: rotate 6s linear infinite;
}

.tech-loading-ring::before {
    content: '';
    position: absolute;
    top: -10px;
    left: 50%;
    width: 20px;
    height: 20px;
    background: #4f46e5;
    border-radius: 50%;
    transform: translateX(-50%);
    box-shadow: 0 0 20px #4f46e5;
}

.tech-loading-particles {
    position: absolute;
    width: 100%;
    height: 100%;
}

.tech-particle {
    position: absolute;
    width: 6px;
    height: 6px;
    background: #818cf8;
    border-radius: 50%;
    animation: particle 3s linear infinite;
    opacity: 0.8;
}

.tech-loading-text {
    margin-top: 40px;
    font-family: 'Courier New', monospace;
    font-size: 1.5rem;
    font-weight: bold;
    color: #a5b4fc;
    text-shadow: 0 0 10px rgba(165, 180, 252, 0.5);
    letter-spacing: 2px;
    display: flex;
    align-items: center;
}

.tech-loading-dots span {
    opacity: 0;
    animation: dots 1.5s infinite;
}

.tech-loading-dots span:nth-child(2) {
    animation-delay: 0.5s;
}

.tech-loading-dots span:nth-child(3) {
    animation-delay: 1s;
}

.tech-loading-countdown {
    position: absolute;
    bottom: 40px;
    right: 40px;
    font-size: 1.2rem;
    color: #818cf8;
    font-family: 'Courier New', monospace;
}

@keyframes gridMove {
    0% {
        background-position: 0 0;
    }
    100% {
        background-position: 40px 40px;
    }
}

@keyframes pulse {
    0% {
        transform: scale(0.95);
        box-shadow: 0 0 40px rgba(79, 70, 229, 0.6);
    }
    100% {
        transform: scale(1.05);
        box-shadow: 0 0 60px rgba(79, 70, 229, 0.8);
    }
}

@keyframes rotate {
    0% {
        transform: rotate(0deg);
    }
    100% {
        transform: rotate(360deg);
    }
}

@keyframes dots {
    0%,
    100% {
        opacity: 0;
    }
    50% {
        opacity: 1;
    }
}

@keyframes particle {
    0% {
        transform: translate(0, 0) scale(0);
        opacity: 0;
    }
    50% {
        opacity: 0.8;
    }
    100% {
        transform: translate(calc((var(--x) - 0.5) * 200px), calc((var(--y) - 0.5) * 200px)) scale(1);
        opacity: 0;
    }
}

/* 为每个粒子设置不同的位置和动画延迟 */
.tech-particle:nth-child(1) {
    --x: 0.2;
    --y: 0.8;
    animation-delay: 0s;
}
.tech-particle:nth-child(2) {
    --x: 0.8;
    --y: 0.2;
    animation-delay: 0.2s;
}
.tech-particle:nth-child(3) {
    --x: 0.5;
    --y: 0.5;
    animation-delay: 0.4s;
}
.tech-particle:nth-child(4) {
    --x: 0.3;
    --y: 0.7;
    animation-delay: 0.6s;
}
.tech-particle:nth-child(5) {
    --x: 0.7;
    --y: 0.3;
    animation-delay: 0.8s;
}
.tech-particle:nth-child(6) {
    --x: 0.1;
    --y: 0.9;
    animation-delay: 1s;
}
.tech-particle:nth-child(7) {
    --x: 0.9;
    --y: 0.1;
    animation-delay: 1.2s;
}
.tech-particle:nth-child(8) {
    --x: 0.4;
    --y: 0.6;
    animation-delay: 1.4s;
}
.tech-particle:nth-child(9) {
    --x: 0.6;
    --y: 0.4;
    animation-delay: 1.6s;
}
.tech-particle:nth-child(10) {
    --x: 0.2;
    --y: 0.3;
    animation-delay: 1.8s;
}
.tech-particle:nth-child(11) {
    --x: 0.8;
    --y: 0.7;
    animation-delay: 2s;
}
.tech-particle:nth-child(12) {
    --x: 0.5;
    --y: 0.2;
    animation-delay: 2.2s;
}

/* 原有样式保持不变 */
.chart-container {
    transition: all 0.3s ease;
    position: relative;
    z-index: 1;
}

.chart-container:hover {
    box-shadow: 0 0 15px rgba(79, 70, 229, 0.3);
}

.summary-card {
    position: relative;
    overflow: hidden;
}

.summary-card::before {
    content: '';
    position: absolute;
    top: -50%;
    left: -50%;
    width: 200%;
    height: 200%;
    background: radial-gradient(circle, rgba(79, 70, 229, 0.1) 0%, transparent 70%);
    animation: rotate 15s linear infinite;
}

.report-section {
    transition: all 0.3s ease;
    position: relative;
    z-index: 1;
}

.report-section:hover {
    box-shadow: 0 0 15px rgba(79, 70, 229, 0.2);
}

.strength-item,
.suggestion-item {
    position: relative;
    transition: all 0.3s ease;
}

.strength-item:hover,
.suggestion-item:hover {
    transform: translateX(5px);
    color: rgba(224, 231, 255, 0.9);
}

.option-card {
    position: relative;
    z-index: 1;
}

.option-card:hover {
    transform: translateY(-2px);
}
</style>
